package com.example.pei.ithinklearnt.view.fragments.innerfragments;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.example.pei.ithinklearnt.Config;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.adapter.ConversationAdapter;
import com.example.pei.ithinklearnt.adapter.base.OnRecyclerViewListener;
import com.example.pei.ithinklearnt.bean.Conversation;
import com.example.pei.ithinklearnt.bean.NewCommentConversation;
import com.example.pei.ithinklearnt.bean.NewFriendConversation;
import com.example.pei.ithinklearnt.bean.PrivateConversation;
import com.example.pei.ithinklearnt.db.NewComment;
import com.example.pei.ithinklearnt.db.NewFriend;
import com.example.pei.ithinklearnt.db.NewFriendManager;
import com.example.pei.ithinklearnt.db.dao.CommentDaoOrder;
import com.example.pei.ithinklearnt.db.dao.PrivateConverDaoOrder;
import com.example.pei.ithinklearnt.event.RefreshEvent;
import com.example.pei.ithinklearnt.event.UnReadCountEvent;
import com.example.pei.ithinklearnt.utils.DialogUtil;
import com.example.pei.ithinklearnt.view.activity.NewCommentActivity;
import com.example.pei.ithinklearnt.view.activity.NewFriendActivity;
import com.example.pei.ithinklearnt.view.base.IMutlipleItem;
import com.example.pei.ithinklearnt.view.customview.EmptyRecyclerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.event.OfflineMessageEvent;

import static com.example.pei.ithinklearnt.adapter.ConversationAdapter.TYPE_CHAT;
import static com.example.pei.ithinklearnt.adapter.ConversationAdapter.TYPE_NEW_COMMENT;
import static com.example.pei.ithinklearnt.adapter.ConversationAdapter.TYPE_NEW_FRIEND;
import static com.example.pei.ithinklearnt.utils.DialogUtil.showSmallDeleteDialog;


public class MessageListsFragment extends Fragment {

    private ConversationAdapter adapter;

    private View rootview;

    @BindView(R.id.swipe_target)
    EmptyRecyclerView rc_view;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout sw_refresh;






    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootview=inflater.inflate(R.layout.messagelists_fragment, container, false);
        ButterKnife.bind(this, rootview);

        //单一布局
        IMutlipleItem<Conversation> mutlipleItem = new IMutlipleItem<Conversation>() {

            @Override
            public int getItemViewType(int postion, Conversation c) {
                if(postion==0)
                    return TYPE_NEW_FRIEND;
                if(postion==1)
                    return TYPE_NEW_COMMENT;
                return TYPE_CHAT;
            }

            @Override
            public int getItemLayoutId(int viewtype) {
                if(viewtype==TYPE_CHAT)
                    return R.layout.item_conversation;
                if(viewtype==TYPE_NEW_FRIEND)
                    return R.layout.header_new_friend;
                if(viewtype==TYPE_NEW_COMMENT)
                    return R.layout.header_new_comment;

                return R.layout.item_conversation;
            }

            @Override
            public int getItemCount(List<Conversation> list) {
                return list.size()+2;
            }
        };

        adapter = new ConversationAdapter(getActivity(),mutlipleItem,null);
        LinearLayoutManager layoutManager=new LinearLayoutManager(getActivity());

        rc_view.setAdapter(adapter);
        rc_view.setLayoutManager(layoutManager);


        setListener();


        return rootview;
    }


    //设置监听
    private void setListener(){
        rootview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                rootview.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                query();
                sw_refresh.finishRefresh(true);
            }
        });

        sw_refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                query();
                sw_refresh.finishRefresh(true);
            }
        });

        adapter.setOnRecyclerViewListener(new OnRecyclerViewListener() {
            @Override
            public void onItemClick(View v,int position) {
                if(position==0){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), NewFriendActivity.class);
                    getContext().startActivity(intent);
                }else if(position==1){
                    Intent intent = new Intent();
                    intent.setClass(getContext(), NewCommentActivity.class);
                    getContext().startActivity(intent);
                }else{
                    adapter.getItem(position).onClick(getActivity());
                }
            }

            @Override
            public boolean onItemLongClick(View v, final int position) {
                if(position<2)
                    return true;
                showSmallDeleteDialog(getContext(), v, new DialogUtil.SmallDeleteDialogListener() {
                    @Override
                    public void click() {
                        adapter.getItem(position).onLongClick(getActivity());
                        adapter.remove(position);
                        updataUnredadCount();
                    }
                });

                return true;
            }
        });
    }


    private void updataUnredadCount(){
        long count=0;
        //更新总的消息未读数量
        count+=BmobIM.getInstance().getAllUnReadCount();
        //更新总的未读新朋友数量
        count+=NewFriendManager.getInstance(getContext()).getNewInvitationCount();
        //更新总的未读评论回复数量
        count+=CommentDaoOrder.getInstance(getContext()).getNewCommentCount();

        EventBus.getDefault().post(new UnReadCountEvent(count));
    }
    /**
     查询本地会话
     */
    public void query(){
        adapter.bindDatas(getConversations());
        adapter.notifyDataSetChanged();

        updataUnredadCount();
    }



    /**
     * 获取会话列表的数据：增加新朋友会话
     * @return
     */
    private List<Conversation> getConversations(){
        //添加会话
        List<Conversation> conversationList = new ArrayList<>();
        conversationList.clear();
        //TODO 会话：4.2、查询全部会话
        List<BmobIMConversation> list = BmobIM.getInstance().loadAllConversation();
        if(list!=null && list.size()>0){
            for (BmobIMConversation item:list){
                switch (item.getConversationType()){
                    case 1://私聊
                        //如果不是被用户手动删除的，则添加
                        if(PrivateConverDaoOrder.getInstance(getContext()).getPrivateConverStatus(item.getConversationId())!=Config.STATUS_DELETED)
                            conversationList.add(new PrivateConversation(item));
                        break;
                    default:
                        break;
                }
            }
        }

            //添加新朋友会话-获取好友请求表中最新一条记录
//            List<NewFriend> friends = NewFriendManager.getInstance(getActivity()).getAllNewFriend();
//            if(friends!=null && friends.size()>0){
//                //不是用户手动删除的，则添加，且添加最新的一条
//                if(friends.get(0).getStatus()!=Config.STATUS_DELETED){
//                    conversationList.add(new NewFriendConversation(friends.get(0)));
//                }
//
//            }



            //添加新的回复会话
//            ArrayList<NewComment> newComments =CommentDaoOrder.getInstance(getActivity()).loadAllNewComments();
//            if(newComments!=null&&newComments.size()>0){
//                //不是用户手动删除的，则添加，且添加最新的一条
//                if(newComments.get(0).getStatus() != Config.STATUS_DELETED) {
//                    conversationList.add(new NewCommentConversation(newComments.get(0)));
//                }
//            }



        //重新排序
        Collections.sort(conversationList);
        return conversationList;
    }



    /**注册自定义消息接收事件
     * @param event
     */
    @Subscribe
    public void onEventMainThread(RefreshEvent event){
        //("---会话页接收到自定义消息---");
        //因为新增`新朋友`这种会话类型
        adapter.bindDatas(getConversations());
        adapter.notifyDataSetChanged();

        updataUnredadCount();
    }

    /**注册离线消息接收事件
     * @param event
     */
    @Subscribe
    public void onEventMainThread(OfflineMessageEvent event){
        //重新刷新列表
        adapter.bindDatas(getConversations());
        adapter.notifyDataSetChanged();


        updataUnredadCount();
    }

    /**注册消息接收事件
     * @param event
     * 1、与用户相关的由开发者自己维护，SDK内部只存储用户信息
     * 2、开发者获取到信息后，可调用SDK内部提供的方法更新会话
     */
    @Subscribe
    public void onEventMainThread(MessageEvent event){
        //重新获取本地消息并刷新列表
        adapter.bindDatas(getConversations());
        adapter.notifyDataSetChanged();

        updataUnredadCount();
    }

    @Override
    public void onResume() {
        super.onResume();
        query();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }
}
